﻿using Abp.Extensions;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

namespace Hengyuantong.SmartRail.Services
{
    public static class AppConfigurations
    {
        static readonly ConcurrentDictionary<string, IConfigurationRoot> ConfigurationCache = new ConcurrentDictionary<string, IConfigurationRoot>();


        public static IConfigurationRoot Get(string path, string environmentName = null, bool addUserSecrets = false)
        {
            var cacheKey = path + "#" + environmentName + "#" + addUserSecrets;
            return ConfigurationCache.GetOrAdd(cacheKey, _ => BuildConfiguration(path, environmentName, addUserSecrets));
        }

        private static IConfigurationRoot BuildConfiguration(string path, string environmentName = null, bool addUserSecrets = false)
        {
            var builder = new ConfigurationBuilder().SetBasePath(path).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            if (!environmentName.IsNullOrWhiteSpace())
            {
                builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true);
                //builder.AddApollo(builder.Build().GetSection("apollo")).AddDefault();
            }

            builder = builder.AddEnvironmentVariables();

            if (addUserSecrets)
            {
                builder.AddUserSecrets((typeof(AppConfigurations)).Assembly);
            }

            return builder.Build();
        }
    }
}
